#include <sstream>
#include <cstdlib>
#include "CKMsg.h"
#include <iostream>



namespace K_Engine
{
    CKMsg::CKMsg() :
        m_nType(),
        m_strErrorMSG(""),
        m_strRuleName(""),
        m_strParams("")
    {}
    
    
    void CKMsg::SetType(int type)
    {
        m_nType = type;
    }
    
    
    void CKMsg::SetRuleName(std::string rulename)
    {
        m_strRuleName = rulename;
    }
    
    
    void CKMsg::SetParams(std::string params)
    {
        m_strParams = params;
    }


    int CKMsg::GetType()
    {
        return m_nType;
    }
    
    
    std::string CKMsg::GetRuleName()
    {
        return m_strRuleName;
    }
    
    
    std::string CKMsg::GetParams()
    {
        return m_strParams;
    }


    std::string CKMsg::FormatMSG()
    {
        std::stringstream ss;
        std::vector<std::string> v;
        int pos = m_strRuleName.find("|");
        while(-1 != pos)
        {
            m_strRuleName.erase(pos, 1);
            pos = m_strRuleName.find("|"); 
        }
        pos = m_strParams.find("|");
        while(-1 != pos)
        {
            m_strParams.erase(pos, 1);
            pos = m_strParams.find("|");
        }
        ss<<m_nType<<"|"<<m_strRuleName<<"|"<<m_strParams;
        return ss.str();
    }
    
    
    void CKMsg::FormatResultMSG(std::string strResult, std::vector<std::string> &v)
    {
        int pos = 0;
        while(true)
        {
            pos = strResult.find("+");
            if (-1 == pos)
            {
                // std::cout<<strResult.c_str()<<std::endl;
                v.push_back(strResult);
                break;
            }
            else if (0 == pos)
            {
                strResult.erase(0, 1);
            }
            else
            {
                // std::cout<<strResult.substr(0, pos).c_str()<<std::endl;
                v.push_back(strResult.substr(0, pos));
                strResult.erase(0, pos + 1);
            }
        }
    }
    
    
    bool CKMsg::ParserMSG(std::string msg)
    {
        //获取type
        int pos = msg.find("|");
        if(-1 == pos)
        {
            m_strErrorMSG = msg;
            return false;
        }
        m_nType = atoi(msg.substr(0, pos).c_str());
        msg.erase(0,pos + 1);
        
        //获取RuleName
        pos = msg.find("|");
        if(-1 == pos)
        {
            m_strErrorMSG = msg;
            return false;
        }
        m_strRuleName = msg.substr(0, pos);
        msg.erase(0,pos + 1);
        
        //获取Params
        pos = msg.find("|");
        if(-1 != pos)
        {
            m_strErrorMSG = msg;
            return false;
        }
        m_strParams = msg;
        return true;
    }
    
    
    std::string CKMsg::GetErrorMSG()
    {
        return m_strErrorMSG;
    }
}
